package com.surfilter.massdata.spark.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.function.Function;

import com.surfilter.massdata.spark.bean.IpBean;
import com.surfilter.massdata.spark.util.ipcheck.IpCheckConstants;

/** 
* @author  hutao
* @date 创建时间：2017年5月22日 下午1:29:48 
* @Description：Ip工具类
* @version 1.0 
* 
**/
public class IpUtils {
	private static Pattern pattern ;
	
	static{
		    String sect = "(([0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])|\\d{2}|\\d{1})";
		    
		  
	        String regular = sect + "\\." + sect + "\\." + sect + "\\." + sect;
	        pattern = Pattern.compile(regular);
	}
	
	/**
	 * get two blocks from begin to end
	 * @param ip
	 * @return
	 */
	public static String getFirstBlockSuffix(String ip){
		String[] strs = ip.trim().split("\\.");
		if(strs.length==4){
			return strs[0];
		}
		return null;
	}
	
	public static String getSecondBlockSuffix(String ip){
		String[] strs = ip.trim().split("\\.");
		if(strs.length==4){
			return strs[0]+"."+strs[1];
		}
		return null;
	}
	
	public static String getSuffixBlocks(String ip,int size){
		if(size==1){
			return getFirstBlockSuffix(ip);
		}
		else{
			return getSecondBlockSuffix(ip);
		}
	}
	
	public static Long ipToLong(String ip) {
        if(ip==null || ip.trim().equals(""))
        	return null;
    	if (!isValidIP(ip)) {
            throw new IllegalArgumentException("invalid ip format");
        }

        Long value = 0L;
        String[] ss = ip.split("\\.");
        for (int i = 0; i < ss.length; i++) {
            value <<= 8;
            value += Long.parseLong(ss[i]);
        }
        for (int i = ss.length; i < 4; i++) {
            value <<= 8;
        }
        return value;
    }
	
	 public static String longToIP(long longIP) {
	        if (longIP < 0) {
	            throw new IllegalArgumentException("invalid value");
	        }

	        StringBuffer sb = new StringBuffer();
	        sb.append(String.valueOf(longIP >>> 24));//直接右移24位
	        sb.append(".");
	        sb.append(String.valueOf((longIP & 0x00FFFFFF) >>> 16)); //将高8位置0，然后右移16位
	        sb.append(".");
	        sb.append(String.valueOf((longIP & 0x0000FFFF) >>> 8));
	        sb.append(".");
	        sb.append(String.valueOf(longIP & 0x000000FF));
	        String value = sb.toString();

	        if (!isValidIP(value)) {
	            throw new IllegalArgumentException("invalid ip format");
	        }
	        return value;
	 }
	 
	 public static boolean isValidIP(String ip) {
		 if(ip != null){
			 return pattern.matcher(ip).matches();
		 }
		   return false;
	 }
	 
	 public static String extractIp(String str){
		 if(str != null){
			 Matcher m = pattern.matcher(str);  
			 if(m.find()){
				 return m.group();
			 }
		 }
		return "";
	 }
	 
	 
	 
}
